package category

import (
	"gitee.com/mootok/mootok/src/constant/strings"
	"gitee.com/mootok/mootok/src/models"
	"gitee.com/mootok/mootok/src/storage/database"
	"gitee.com/mootok/mootok/src/utils/logging"
	"gitee.com/mootok/mootok/src/web/api"
	"gitee.com/mootok/mootok/src/web/common/response"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"net/http"
)

type ApiCategoryImpl struct {
}

func (i *ApiCategoryImpl) CreateCategory(c *gin.Context) {
	var req api.CreateCategoryReq
	var err error

	logger := logging.LogService("Category.Create")

	err = c.BindJSON(&req)
	if err != nil {
		response.FailWithMsg(c, http.StatusBadRequest, strings.ParamsErrorCode, strings.ParamsError)
		return
	}

	category := &models.Category{
		Name:      *req.Name,
		IsVirtual: *req.Virtual,
	}

	if err = database.Client.Create(category).Error; err != nil {
		logger.WithFields(logrus.Fields{
			"name":    *req.Name,
			"virtual": *req.Virtual,
		}).Errorf("Error saving to db:%v", err)
		response.FailWithMsg(c, http.StatusInternalServerError,
			strings.DataBaseInsertErrorCode, strings.InternalServiceError)
		return
	}

	response.SuccessWithDetail(c, strings.SuccessCode, strings.Success, &api.CategoryInfo{
		Id:      &category.ID,
		Name:    &category.Name,
		Virtual: &category.IsVirtual,
	})
	logger.WithFields(logrus.Fields{
		"name":    *req.Name,
		"virtual": *req.Virtual,
	}).Errorf("Category created.")
}
